package memorphic.logging
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import mx.formatters.DateFormatter;
	import mx.logging.AbstractTarget;
	import mx.logging.LogEvent;
	
	public class FileLogTarget extends AbstractTarget
	{
		private var message:String;
		private var logDate:Date;
		private var logDateFormatter:DateFormatter;
		private var timeFormatter:DateFormatter;
		[Bindable]
		private var loginDateStr:String;
		[Bindable]
		private var loginTimeStr:String;

		public override function logEvent(event:LogEvent):void
		{
			logDate = new Date();
			
			logDateFormatter  = new DateFormatter();
			logDateFormatter.formatString = "DD/MM/YYYY";
			loginDateStr = logDateFormatter.format(logDate);
			
			timeFormatter = new DateFormatter();
			timeFormatter.formatString = "HH:NN:SS";
			loginTimeStr = timeFormatter.format(logDate); 
			
			message = loginDateStr + " "+ loginTimeStr + " " + "[INFO] " + event.message + "\n";

			var formatter:DateFormatter = new DateFormatter();
			formatter.formatString = "YYYY-MMM-DD-JJ-NN-SS";

//			var file:File = File.documentsDirectory.resolvePath("lmg-" + formatter.format(new Date())  + ".log");
			var file:File = File.documentsDirectory.resolvePath("lmg.log");
			var fileStr:FileStream = new FileStream();
			fileStr.open(file, FileMode.APPEND);
//			fileStr.openAsync(file, FileMode.APPEND);
			
			message = message.replace(/\r/g, "\n");
			message = message.replace(/\n/g, File.lineEnding);
			
			fileStr.writeUTFBytes(message);
			fileStr.close();
			
		}
	}
}